#!/usr/bin/env perl

use strict;
use warnings;

use FindBin;
use lib "$FindBin::Bin/../lib";

use MusicBrainz::Server::Context;
use MusicBrainz::Server::Data::Utils qw( placeholders );
use Sql;
use Try::Tiny;

use constant MAX_TOP_LANGUAGES => 20;

# Always include the six official UN languages and the "Multiple languages"
# pseudo language.
#
use constant PRESELECTED_LANGUAGES => qw(
    ara eng fra spa rus zho mul
);


my $c = MusicBrainz::Server::Context->create_script_context;
my $sql = $c->sql;
my $ro_sql = $c->prefer_ro_sql;

#
# Set the frequency attribute of the language table.
#

my %languages = ( );

foreach my $code ( PRESELECTED_LANGUAGES )
{
    my $lang = $c->model('Language')->find_by_code($code);
    $languages{ $lang->id } = 1;
}

#
# Calculate language frequencies
#

$ro_sql->select(<<'EOF', MAX_TOP_LANGUAGES + scalar(PRESELECTED_LANGUAGES));
    SELECT              language, COUNT(*)
    FROM                release
    WHERE NOT   language IS NULL
    GROUP BY    language
    ORDER BY    COUNT(*) DESC
    LIMIT               ?;
EOF


# put at most MAX_TOP_LANGUAGES into %languages
while ( my ($language, $count) = $ro_sql->next_row() )
{
    last if keys(%languages) >= MAX_TOP_LANGUAGES;

    $languages{ $language } = 1;
}

$ro_sql->finish();

print 'New top languages: ', join(' ', keys %languages), "\n";

#
# Start transaction here. No strict isolation required up to now.
#

try
{
    $sql->begin;

    my @top_languages = grep { m/^\d+$/ } keys %languages;

    # ignore languages with a frequency of 0 (never displayed in the UI)

    # reset current top languages to frequency 1 (default frequency)
    $sql->do(
        'UPDATE language SET frequency = ? WHERE frequency = ?',
        1, 2
    );

    # set new top languages to 2 (displayed in the short list)
    $sql->do(
        'UPDATE language SET frequency = 2
          WHERE id IN (' . placeholders(@top_languages) . ')',
        @top_languages
    );

    $sql->commit;
}
catch
{
    print "ERROR: Setting frequencies didn't work\n";
    print $_;
    $sql->rollback();
    exit 1;
};

#
# Invalidate Redis entries to use the new values sooner.
#

$c->model('Language')->_delete_all_from_cache;

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2005 Robert Kaye

This file is part of MusicBrainz, the open internet music database,
and is licensed under the GPL version 2, or (at your option) any
later version: http://www.gnu.org/licenses/gpl-2.0.txt

=cut
